package week.six;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import javax.microedition.khronos.opengles.GL10;

public class Box {

	private float x;
	private float y;
	private float z;
	private Vec3 pos;
	private Vec3 rot;
	
	private float vertices[];
	
	private void setVertices() {
		vertices = new float[] {
// http://doc.qt.nokia.com/4.8/opengl-cube.html
			// Front 1
			-x, y, z,	// 0
			 x, y, z,	// 1
			-x,-y, z,	// 2
			// Front 2
			 x, y, z,	// 1
			 x,-y, z,	// 3
			-x,-y, z,	// 2
			// Right 1
			 x, y, z,	// 4
			 x, y,-z,	// 5
			 x,-y, z,	// 6
			// Right 2 
			 x,-y,-z,	// 7
			 x, y,-z,	// 5
			 x,-y, z,	// 6
			// Back 1
			 x, y,-z,	// 8
			-x, y,-z,	// 9
			 x,-y,-z,	// 10
			// Back 2
			-x, y,-z,	// 9
			-x,-y,-z,	// 11
			 x,-y,-z,	// 10
			// Left 1
			-x, y,-z,	// 12
			-x, y, z,	// 13
			-x,-y,-z,	// 14
			// Left 2
			-x, y, z,	// 13
			-x,-y, z,	// 15
			-x,-y,-z,	// 14
			// Bottom 1
			-x, y,-z,	// 16
			 x, y,-z,	// 17
			-x, y, z,	// 18
			// Bottom 2
			 x, y,-z,	// 17 
			 x, y, z,	// 19
			-x, y, z,	// 18 
			// Top 1
			-x,-y, z,	//20
			 x,-y, z,	//21
			-x,-y,-z,	//22
			// Top 2
			 x,-y, z,	//21
			 x,-y,-z	//23
			-x,-y,-z,	//22
		};
	}
	
	private FloatBuffer vertexBuffer;
//	private FloatBuffer colourBuffer;
	
	public void setRotation(Vec3 rotation) {
		this.rot = rotation;
	}
	
	public void setPosition(Vec3 position) {
		this.pos = position;
	}
	
	private void setBuffers() {
		// A float has 4 bytes to multiply length by 4
		ByteBuffer bb = ByteBuffer.allocateDirect(vertices.length * 4);
		bb.order(ByteOrder.nativeOrder());
		vertexBuffer = bb.asFloatBuffer();
		vertexBuffer.put(vertices);
		vertexBuffer.position(0);
	}
	
	public Box(Vec3 size, Vec3 position, Vec3 rotation) {
		x = size.x/2;
		y = size.y/2;
		z = size.z/2;
		this.pos = position;
		this.rot = rotation;
		setVertices();
		setBuffers();
	}
	
	public void draw(GL10 gl) {
		gl.glTranslatef(pos.x, pos.y, pos.z);
		gl.glRotatef(rot.x, 1, 0, 0);
		gl.glRotatef(rot.y, 0, 1, 0);
		gl.glRotatef(rot.y, 0, 0, 1);
		gl.glFrontFace(GL10.GL_FLOAT);
		gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
		gl.glColor4f(0.0f, 0.0f, 0.0f, 1.0f);
		gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
		//gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
		gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, vertices.length / 3);
		gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
		//gl.glDisableClientState(GL10.GL_COLOR_ARRAY);
	}
}
